package com.service.impl;

import com.common.exception.db.InsertException;
import com.common.exception.db.UpdateException;
import com.dao.OrderDao;
import com.dto.in.OrderListInfo;
import com.entity.*;
import com.service.OrderService;
import com.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.*;


@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDao orderDao;

    @Override
    public List<RecordInfo> orderRecord(Integer stdUserId,Integer teaUserId) {
        if(stdUserId == null){
            return orderDao.orderRecord1(teaUserId);
        }else{
            return orderDao.orderRecord(stdUserId);
        }
    }

    @Override
    public BigDecimal findTeacherHourPrice(Integer teaUserId) {
        BigDecimal money = orderDao.findTeacherHourPrice(teaUserId);
        return money;
    }

    @Override
    public StudentInfo findZiJiGerMsg(Integer userId) {
        return orderDao.findZiJiGerMsg(userId);
    }

    @Override
    public RecordInfo orderDetails(Integer orderId) {
        RecordInfo recordInfo=orderDao.orderDetails(orderId);
        //老师的可教科目
        List<SubjectInfo> subjectName = orderDao.findSubjectName(recordInfo.getTeaUserId());
        //家长的求教科目查询
        List<SubjectInfo> qiuSubjectName = orderDao.findSubjectName(recordInfo.getStdUserId());
        recordInfo.setSubjectName(subjectName);
        recordInfo.setQiuSubjectName(qiuSubjectName);
        return recordInfo;
    }

    @Override
    public int deleteOrder(Integer orderId) {
        return orderDao.deleteOrder(orderId);
    }

    @Override
    @Transactional
    public int addOrder(OrderListInfo orderListInfo) {
        String result = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date().getTime());
        String[] split = result.split("-");
        String split1="";
        for (String s : split) {
            split1+=s;
        }
        int a = (int)((Math.random()*9+1)*1000);
        String uuid = "DD"+split1+a;
        orderListInfo.setUuid(uuid);
        int addorder=orderDao.addOrder(orderListInfo);
        if(addorder>0){
            int id = orderListInfo.getId();
            for(int i=1; i<=orderListInfo.getClassTime(); i++){
                String ke = i+"课时";
               int count = orderDao.addSmallOrder(id,ke,orderListInfo.getPrice());
               if(count < 1){
                   throw new InsertException("新增失败");
               }
            }
            return id;
        }else{
            throw new InsertException("新增失败");
        }
    }

    @Override
    public int updateRecordStatus(Integer id) {
        return orderDao.updateRecordStatus(id);
    }

    @Override
    public ParentMsgInfo findOrderPayMsg(Integer id) {
        return orderDao.findOrderPayMsg(id);
    }

    @Override
    @Transactional
    public int updateOrderStatus(Integer id, String nonceStr, Integer userId,BigDecimal yb,BigDecimal fhPrice,BigDecimal totalPrice,BigDecimal zzPrice) {
        BigDecimal money = orderDao.findUserMoney(userId);   //先查余额   余额 + 赠送余额
        BigDecimal ly_price = orderDao.findUserMoney1(userId);   // 余额
        BigDecimal gift_price = orderDao.findUserMoney2(userId);   // 赠送余额
        BigDecimal zz_price = new BigDecimal(Double.toString(0.01));
        if(zzPrice.compareTo(zz_price) == 0){ //如果zzPrice == 0.01  就为0
            zz_price = new BigDecimal(0);
        }else{
            zz_price = zzPrice;
        }
        if(money.compareTo(yb) == 0){        //如果余额在此期间没有变化
            BigDecimal a = new BigDecimal(0);
            if(fhPrice.compareTo(a) == 0) {                      //没有Y币剩余  直接所有清空
                int count = orderDao.updateUserMoney1(userId);
                if (count < 1) {
                    throw new UpdateException("修改失败");
                }
            }else{
//                BigDecimal giftMoney = orderDao.findUserGiftMoney(userId);    //查赠送余额是否够扣除，如果够 就扣 余额不变
                if(gift_price.compareTo(fhPrice) != -1){  //够扣
                    //新增  如果够扣  查出扣了多少赠送钱数  然后吧他放到record 的gift_price
                    gift_price = totalPrice;
                    ly_price = new BigDecimal(0);
                    int count = orderDao.updateUserMoney2(userId,totalPrice);
                    if(count != 1){
                        throw new UpdateException("修改失败");
                    }
                }else{   //不够扣   直接赠送清0  余额为fhPrice
                    ly_price = ly_price.subtract(fhPrice);
                    gift_price = new BigDecimal(0);
                    int count = orderDao.updateUserMoney3(userId,fhPrice);
                    if(count != 1){
                        throw new UpdateException("修改失败");
                    }
                }
            }
        }
           int count = orderDao.updateOrderStatus(id, nonceStr,ly_price,gift_price,zz_price);
            if (count > 0) {
                return count;
            } else {
                throw new UpdateException("修改失败");
            }
    }

    @Override
    public List<RecordOrderInfo> findSmallOrder(Integer id) {
        List<RecordOrderInfo> list = orderDao.findSmallOrder(id);
        return list;
    }

    @Override
    @Transactional
    public int confirmEnd(Integer id, Integer recordId,BigDecimal price) {
        //1.查这个订单是不是最后一个
        List<RecordOrderInfo> list = orderDao.findSmallOrder(recordId);
        Date now = new Date();
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTime(now);
        calendar.add(Calendar.DAY_OF_MONTH,+7);
        Date date = calendar.getTime();
        int num = 1;
        int edit;
        for(int i=0; i < list.size(); i++){
            if(list.get(i).getId().equals(id)){   //如果等于
                num = num + i;
            }
        }
        Integer teaUserId = orderDao.findTeacherUserId(recordId);
        if(num != 1){  //不是第一个
            for(int o=0; o < num - 1; o++){
                RecordOrderInfo recordOrderInfo = list.get(o);
                if(recordOrderInfo.getIsConfirm().equals("NO")){
                    return -1;
                }
            }
        }
        if(num >= list.size()){    //如果是最后一个
            edit = orderDao.updateOrderIsEnd(recordId);    //去修改订单状态为END
            if(edit != 1){
                throw new UpdateException("修改订单结束状态失败");
            }
        }
       edit = orderDao.updateUserMoney4(teaUserId,price);
        if(edit > 0){
            edit = orderDao.updateRecordOrderStatus(id);
            if(edit > 0){
                String uuid = UUIDUtil.get32UUID();
                edit = orderDao.insertBill(teaUserId,price,1,"课程结算",uuid);
                    if(edit > 0){
                        if(num >= list.size()){
                            return 2;   //最后一个返回2  直接重新刷新页面
                        }else{
                            return 1;    //不变页面
                        }
                    }else{
                        throw new InsertException("新增流水失败");
                    }
            }else{
                throw new InsertException("修改小订单状态失败");
            }
        }else{
            throw new InsertException("新增老师冻结金额失败");
        }



    }

    @Override
    @Transactional
    public int insertRefund(Integer recordId) {
        int count = orderDao.insertRefund(recordId);
        if(count > 0){
            count = orderDao.updateOrderRefundStatus(recordId);
            if(count > 0){
                return count;
            }else{
                throw new UpdateException("修改失败");
            }
        }else{
            throw new InsertException("新增失败");
        }
    }

    @Override
    public int savePath(Integer recordId, String thisLocation, String thisLat, String thisLog, String aimLocation, String aimLat, String aimLog) {
        int count = orderDao.findOrderLocationCount(recordId);
        if(count < 5){
            count = orderDao.savePath(recordId,thisLocation,thisLat,thisLog,aimLocation,aimLat,aimLog);
            if(count > 0){
                return 1;
            }else{
                return 0;
            }
        }else{
            return -1;
        }
    }

    @Override
    public List<LoginInfo> findRanking(Integer limit, Integer type) {
        if(type == 1){
           return orderDao.findDayRanking(limit);
        }else if(type == 2){
            return orderDao.findWeekRanking(limit);
        }else{
            return orderDao.findMonthRanking(limit);
        }
    }

    @Override
    public List<LoginInfo> findJiLuList(Integer limit) {
        return orderDao.findJiLuList(limit);
    }
}
